package com.lee.forum.mq.publisher;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: lishuo
 * Date: 2024-02-18
 * Time: 11:32
 */

import com.lee.forum.config.AppConfig;
import com.lee.forum.exception.ApplicationException;
import com.lee.forum.model.Message;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFutureCallback;

import java.util.UUID;

/**
 * 用于投递（生成）产消息的类
 */
@Slf4j
@Component
public class MqPoster {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void postRealTimeMessage(Message message) {
        // 1.创建CorrelationData，并指定消息ID
        CorrelationData cd = new CorrelationData(UUID.randomUUID().toString());
        // 2.给Future添加ConfirmCallback
        cd.getFuture().addCallback(new ListenableFutureCallback<CorrelationData.Confirm>() {
            @Override
            public void onFailure(Throwable ex) {
                // 基本不会触发
                log.error("消息回调失败",ex);
            }

            @Override
            public void onSuccess(CorrelationData.Confirm result) {
                // 这里执行回调
                if (result.isAck()) {
                    // 消息发送成功
                    log.debug("消息发送成功，收到 ack");
                } else {
                    // 消息发送失败
                    log.debug("消息发送失败，收到 nack: "+result.getReason());
                    // 这里暂时先记录异常
                    throw new ApplicationException("消息发送失败，收到 nack: "+result.getReason());
                    // 重传等业务逻辑...
                }
            }
        });
        // 消息投递
        rabbitTemplate.convertAndSend(AppConfig.MSG_EXCHANGE_NAME,AppConfig.MSG_ROUTINGKEY,message,cd);
        log.debug("消息投递成功："+message);

    }
}
